import config from '@/config';
import storage from '@/utils/storage';
import constant from '@/utils/constant';
import { toast } from '@/utils/common';
import { login, logout, getInfo, getDictList } from '@/api/login';
import { getUserAuthority, updateUserPwd } from '@/api/system/user.js';
import {
  setToken,
  removeToken,
  removeOpenId,
  removeUserCode,
  setDicData,
  getDriverId,
  setDriverId,
  getOpenId,
  getTenantId,
  setAccountIdentity
} from '@/utils/auth';

const user = {
  state: {
    id: 0, // 用户编号
    name: storage.get(constant.name),
    phone: storage.get(constant.phone),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    menus: storage.get(constant.menus),
    userinfo: {},
    needAuth: true,
    isLogin: false,
    curTypeColor: '#409EFE', //'#409EFE',// '#D22C2C'
    dicData: []
  },

  mutations: {
    SET_DIC_DATA: (state, dicData) => {
      state.dicData = dicData;
    },
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_USER_INFO: (state, datas) => {
      state.name = datas.name;
      state.phone = datas.phone;
      storage.set(constant.phone, datas.phone);
      storage.set(constant.name, datas.name);
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
      storage.set(constant.avatar, avatar);
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
      storage.set(constant.roles, roles);
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
      storage.set(constant.permissions, permissions);
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus;
      storage.set(constant.menus, menus);
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      return new Promise((resolve, reject) => {
        login(username, password)
          .then((res) => {
            console.log(res, '这是登录后获取的res');
            // 设置 token
            commit('SET_USER_INFO', {
              name: username,
              phone: res.data.userPhone
            });
            setToken(res.data);
            setDriverId(res.data.userId);
            setAccountIdentity(res.data.accountIdentity);
            resolve(res.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 读取菜单权限数据
    GetUserAuthority({ commit, state }) {
      return new Promise((resolve, reject) => {
        let data = {
          enterId: getTenantId(),
          userId: getDriverId()
        };
        getUserAuthority(data)
          .then((res) => {
            console.log(res, '这是用户菜单权限===');
            // commit('SET_MENUS', res.data)
            uni.setStorageSync('vuex_menus', res.data);
            resolve(res);
          })
          .catch((error) => {
            toast(error);
          });
      });
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        let data = {
          enterId: getTenantId(),
          userId: getDriverId()
        };
        getInfo(data)
          .then((res) => {
            res = res.data; // 读取 data 数据
            const user = res.user;
            const avatar =
              user == null || user.avatar === '' || user.avatar == null
                ? state.curTypeColor == '#D22C2C'
                  ? config.baseImgUrl + '/profile_red.png'
                  : config.baseImgUrl + '/profile_blue.png'
                : user.avatar;
            const nickname =
              user == null || user.nickname === '' || user.nickname == null
                ? ''
                : user.nickname;
            if (res.roles && res.roles.length > 0) {
              commit('SET_ROLES', res.roles);
              commit('SET_PERMISSIONS', res.permissions);
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT']);
            }

            // commit('SET_NAME', nickname)
            commit('SET_AVATAR', avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 修改密码
    UpdateUserPwd({ commit }, data) {
      return new Promise((resolve, reject) => {
        updateUserPwd(data)
          .then((res) => {
            console.log(res, '这是接口返回的结果111');
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户字典
    GetUserDictData({ commit }) {
      // 接口获取用户所有字典
      return new Promise((resolve, reject) => {
        getDictList()
          .then((res) => {
            if (res.code == 0) {
              console.log('SET_DIC_DATA', res.data);
              commit('SET_DIC_DATA', res.data);
              setDicData(res.data);
              resolve();
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_ROLES', []);
            commit('SET_PERMISSIONS', []);
            removeToken();
            removeOpenId();
            removeUserCode();
            storage.clean();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
  }
};

export default user;
